package validator

import (
	"crypto/x509"
	"encoding/pem"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"os"
	"strings"
	"time"

	"gitee.com/yanwc/license/internal/validator"
)

// NewLicenseValidator 创建许可证验证器 publicKeyPEM 支持文件路径和内容
func NewLicenseValidator(licensePath, publicKeyPEM string) (*validator.LicenseValidator, error) {
	publicKeyContent := publicKeyPEM
	if strings.HasSuffix(publicKeyPEM, ".pem") {
		// 读取文件
		f, err := os.Open(publicKeyPEM)
		if err != nil {
			slog.Error("License: Failed to open public key pem file ", "error", err, "public_key_pem", publicKeyPEM)
			return nil, err
		}
		data, err := io.ReadAll(f)
		if err != nil {
			slog.Error("License: Failed read public key pem file", "error", err, "public_key_pem", publicKeyPEM)
			return nil, err
		}

		publicKeyContent = string(data)

	}
	block, _ := pem.Decode([]byte(publicKeyContent))
	if block == nil {
		slog.Error("License: Unable to decode the PEM-formatted public key.", "public_key_pem", publicKeyPEM)
		return nil, errors.New("unable to decode the PEM-formatted public key")
	}

	pubKey, err := x509.ParsePKCS1PublicKey(block.Bytes)
	if err != nil {
		slog.Error("License: License: Failed to parse PKCS1 public key", "error", err)
		return nil, fmt.Errorf("license: Failed to parse PKCS1 public key: %w", err)
	}

	return validator.NewLicenseValidator(
		pubKey,
		licensePath,
		time.Time{}), nil
}
